from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, ForeignKey, Enum, JSON
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.database import Base
import enum


class APIStatus(str, enum.Enum):
    """API 状态枚举"""
    DRAFT = "draft"
    PUBLISHED = "published"
    DEPRECATED = "deprecated"
    MAINTENANCE = "maintenance"


class APIMethod(str, enum.Enum):
    """API 方法枚举"""
    GET = "GET"
    POST = "POST"
    PUT = "PUT"
    DELETE = "DELETE"


class APIService(Base):
    """API 服务模型"""
    __tablename__ = "api_services"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False, index=True)
    description = Column(Text, nullable=True)
    path = Column(String(200), nullable=False, unique=True)  # API 路径
    method = Column(Enum(APIMethod), default=APIMethod.GET)
    status = Column(Enum(APIStatus), default=APIStatus.DRAFT)
    
    # API 配置
    datasource_id = Column(Integer, ForeignKey("datasources.id"), nullable=True)
    query_sql = Column(Text, nullable=True)  # 查询 SQL
    request_params = Column(JSON, nullable=True)  # 请求参数配置
    response_format = Column(JSON, nullable=True)  # 响应格式配置
    
    # 限制配置
    rate_limit = Column(Integer, default=1000)  # 每分钟请求限制
    max_rows = Column(Integer, default=1000)    # 最大返回行数
    timeout = Column(Integer, default=30)       # 超时时间（秒）
    
    # 认证配置
    auth_required = Column(Boolean, default=True)
    allowed_roles = Column(JSON, nullable=True)  # 允许的角色列表
    
    # 创建信息
    creator_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    datasource = relationship("DataSource")
    creator = relationship("User")
    call_logs = relationship("APICallLog", back_populates="api_service")


class APICallLog(Base):
    """API 调用日志模型"""
    __tablename__ = "api_call_logs"

    id = Column(Integer, primary_key=True, index=True)
    api_service_id = Column(Integer, ForeignKey("api_services.id"), nullable=False)
    
    # 调用信息
    client_ip = Column(String(45), nullable=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
    request_method = Column(String(10), nullable=False)
    request_path = Column(String(500), nullable=False)
    request_params = Column(JSON, nullable=True)
    request_headers = Column(JSON, nullable=True)
    
    # 响应信息
    response_status = Column(Integer, nullable=False)
    response_size = Column(Integer, nullable=True)  # 响应大小（字节）
    response_time = Column(Integer, nullable=True)  # 响应时间（毫秒）
    
    # 错误信息
    error_message = Column(Text, nullable=True)
    
    # 时间戳
    call_time = Column(DateTime(timezone=True), server_default=func.now())
    
    # 关系
    api_service = relationship("APIService", back_populates="call_logs")
    user = relationship("User") 